package io.gitee.twoke.generator.engine.impl.context;

import io.gitee.twoke.generator.engine.impl.cfg.GenerateEngineConfigurationImpl;
import io.gitee.twoke.generator.engine.impl.cfg.TransactionContext;
import io.gitee.twoke.generator.engine.impl.interceptor.CommandContext;

import java.util.Stack;

public class Context {

    protected static ThreadLocal<Stack<CommandContext>> commandContextThreadLocal = new ThreadLocal<Stack<CommandContext>>();
    protected static ThreadLocal<Stack<GenerateEngineConfigurationImpl>> generateEngineConfigurationThreadLocal = new ThreadLocal<Stack<GenerateEngineConfigurationImpl>>();
    protected static ThreadLocal<Stack<TransactionContext>> transactionContextThreadLocal = new ThreadLocal<Stack<TransactionContext>>();


    public static TransactionContext getTransactionContext() {
        Stack<TransactionContext> stack = getStack(transactionContextThreadLocal);
        if (stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }

    public static void setTransactionContext(TransactionContext transactionContext) {
        getStack(transactionContextThreadLocal).push(transactionContext);
    }

    public static void removeTransactionContext() {
        getStack(transactionContextThreadLocal).pop();
    }

    protected static <T> Stack<T> getStack(ThreadLocal<Stack<T>> threadLocal) {
        Stack<T> stack = threadLocal.get();
        if (stack == null) {
            stack = new Stack<T>();
            threadLocal.set(stack);
        }
        return stack;
    }


    public static GenerateEngineConfigurationImpl getGenerateEngineConfiguration() {
        Stack<GenerateEngineConfigurationImpl> stack = getStack(generateEngineConfigurationThreadLocal);
        if (stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }

    public static void setGenerateEngineConfiguration(GenerateEngineConfigurationImpl processEngineConfiguration) {
        getStack(generateEngineConfigurationThreadLocal).push(processEngineConfiguration);
    }

    public static void removeGenerateEngineConfiguration() {
        getStack(generateEngineConfigurationThreadLocal).pop();
    }

    public static CommandContext getCommandContext() {
        Stack<CommandContext> stack = getStack(commandContextThreadLocal);
        if (stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }

    public static void setCommandContext(CommandContext commandContext) {
        getStack(commandContextThreadLocal).push(commandContext);
    }

    public static void removeCommandContext() {
        getStack(commandContextThreadLocal).pop();
    }

}
